#!/usr/bin/env python3
"""
简单的过滤器功能测试脚本
验证过滤器功能是否正常工作
"""

import requests
import json
import time

def test_filter_functionality():
    """测试过滤器功能"""
    print("=== 过滤器功能测试 ===")
    
    base_url = 'http://localhost:5000'
    
    # 检查服务器是否运行
    try:
        response = requests.get(f'{base_url}/statistics', timeout=5)
        if response.status_code != 200:
            print(f"服务器响应异常: {response.status_code}")
            return False
    except Exception as e:
        print(f"无法连接到服务器 {base_url}: {e}")
        print("请确保服务器正在运行在 localhost:5000")
        return False
    
    print("✓ 服务器连接正常")
    
    # 测试用例
    test_cases = [
        {
            'name': '测试1: 品种过滤',
            'request': {
                'filters': [{'field': 'symbol', 'operator': 'equals', 'value': 'AAPL'}]
            }
        },
        {
            'name': '测试2: 方向过滤',
            'request': {
                'filters': [{'field': 'direction', 'operator': 'equals', 'value': 'Long'}]
            }
        },
        {
            'name': '测试3: 数值范围过滤',
            'request': {
                'filters': [
                    {'field': 'net_profit', 'operator': 'greater_than', 'value': '0'},
                    {'field': 'net_profit', 'operator': 'less_than', 'value': '1000'}
                ],
                'logic': 'and'
            }
        },
        {
            'name': '测试4: 多条件组合',
            'request': {
                'filters': [
                    {'field': 'symbol', 'operator': 'equals', 'value': 'TSLA'},
                    {'field': 'direction', 'operator': 'equals', 'value': 'Long'}
                ],
                'logic': 'and'
            }
        },
        {
            'name': '测试5: OR逻辑',
            'request': {
                'filters': [
                    {'field': 'symbol', 'operator': 'equals', 'value': 'AAPL'},
                    {'field': 'symbol', 'operator': 'equals', 'value': 'TSLA'}
                ],
                'logic': 'or'
            }
        }
    ]
    
    success_count = 0
    
    for i, test_case in enumerate(test_cases, 1):
        print(f"\n{i}. {test_case['name']}")
        print(f"   请求: {test_case['request']}")
        
        try:
            # 发送请求
            response = requests.get(
                f'{base_url}/statistics/chart_data',
                params={'config': json.dumps(test_case['request'])},
                timeout=10
            )
            
            if response.status_code == 200:
                try:
                    data = response.json()
                    
                    # 检查数据类型
                    if isinstance(data, dict) and 'trades' in data:
                        trades = data['trades']
                        total = data.get('total', len(trades))
                        print(f"   ✓ 成功返回 {len(trades)} 条记录 (总计: {total})")
                        success_count += 1
                        
                        # 显示前3条记录的摘要
                        for j, record in enumerate(trades[:3]):
                            if isinstance(record, dict):
                                symbol = record.get('symbol', 'N/A')
                                direction = record.get('direction', 'N/A')
                                net_profit = record.get('net_profit', 'N/A')
                                print(f"     记录 {j+1}: {symbol} - {direction} - {net_profit}")
                            else:
                                print(f"     记录 {j+1}: {record}")
                    elif isinstance(data, list):
                        print(f"   ✓ 成功返回 {len(data)} 条记录")
                        success_count += 1
                        
                        # 显示前3条记录的摘要
                        for j, record in enumerate(data[:3]):
                            if isinstance(record, dict):
                                symbol = record.get('symbol', 'N/A')
                                direction = record.get('direction', 'N/A')
                                net_profit = record.get('net_profit', 'N/A')
                                print(f"     记录 {j+1}: {symbol} - {direction} - {net_profit}")
                            else:
                                print(f"     记录 {j+1}: {record}")
                    else:
                        print(f"   ⚠ 返回数据格式异常: {type(data)}")
                        print(f"   响应内容: {str(data)[:200]}...")
                        
                except json.JSONDecodeError:
                    print(f"   ✗ JSON解析失败")
                    print(f"   响应内容: {response.text[:200]}...")
                    
            else:
                print(f"   ✗ HTTP错误: {response.status_code}")
                print(f"   响应内容: {response.text[:200]}...")
                
        except Exception as e:
            print(f"   ✗ 请求异常: {e}")
        
        time.sleep(0.5)  # 避免请求过快
    
    print(f"\n=== 测试结果 ===")
    print(f"总测试数: {len(test_cases)}")
    print(f"成功数: {success_count}")
    print(f"成功率: {success_count/len(test_cases)*100:.1f}%")
    
    return success_count == len(test_cases)

def test_specific_endpoints():
    """测试特定端点"""
    print("\n=== 特定端点测试 ===")
    
    base_url = 'http://localhost:5000'
    
    endpoints = [
        '/statistics',
        '/statistics/chart_data',
        '/statistics/saved_chart_configs'
    ]
    
    for endpoint in endpoints:
        try:
            response = requests.get(f'{base_url}{endpoint}', timeout=5)
            print(f"{endpoint}: {response.status_code}")
            
            if response.status_code == 200:
                try:
                    data = response.json()
                    print(f"  ✓ JSON响应，数据类型: {type(data)}")
                    if isinstance(data, list):
                        print(f"  ✓ 列表长度: {len(data)}")
                    elif isinstance(data, dict):
                        print(f"  ✓ 字典键: {list(data.keys())[:5]}")
                except:
                    print(f"  ✓ 非JSON响应")
            else:
                print(f"  ✗ 错误响应: {response.text[:100]}...")
                
        except Exception as e:
            print(f"  ✗ 请求异常: {e}")

def main():
    """主函数"""
    print("简单过滤器功能测试")
    print("=" * 40)
    
    # 测试特定端点
    test_specific_endpoints()
    
    # 测试过滤器功能
    success = test_filter_functionality()
    
    if success:
        print("\n✓ 所有测试通过！过滤器功能正常工作。")
    else:
        print("\n⚠ 部分测试失败，请检查上述输出。")
    
    print("\n使用说明:")
    print("1. 确保服务器运行在 localhost:5000")
    print("2. 数据库中有测试数据")
    print("3. 手动访问 http://localhost:5000/statistics 测试UI")

if __name__ == '__main__':
    main() 